package com.xmtlxx.common.utils.image;

import com.xmtlxx.common.utils.file.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 对图片添加水印
 *
 * @author RonyChan
 * @since 2022/6/6 00:11
 */
public class ImageUtils {
    private ImageUtils() {
    }

    public static void pressText(String filePath, String pressText, String fontName, int fontStyle, int fontSize, Color color, int x, float alpha, int LineHeight){
        File file = new File(filePath);
        pressText(file,pressText,fontName,fontStyle,fontSize,color,x,alpha,LineHeight);
    }

    /**
     * 添加文字水印
     *
     * @param file      目标图片路径，如：C://myPictrue//1.jpg
     * @param pressText 水印文字， 如：中国证券网
     * @param fontName  字体名称，    如：宋体
     * @param fontStyle 字体样式，如：粗体和斜体(Font.BOLD|Font.ITALIC)
     * @param fontSize  字体大小，单位为像素
     * @param color     字体颜色
     * @param x         水印文字距离目标图片左侧的偏移量，如果x<0, 则在正中间
     * @param alpha     透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)
     * @Param lineHeight水印文字间的行高
     */
    public static void pressText(File file, String pressText, String fontName, int fontStyle, int fontSize, Color color, int x, float alpha, int LineHeight) {
        try {

            //获取图片格式（如png,jpg等）
            String PICTRUE_FORMATE = file.getName().substring(file.getName().indexOf(".") + 1);
            Image image = ImageIO.read(file);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            System.out.println("Height："+height);
            String textStr[] = pressText.split("_");//解析地理位置，经度，纬度

            Integer w60 = Double.valueOf(width*0.9).intValue();

            int length = 1;
            for(String str : textStr){
                length = str.length() < length ? length : str.length();
                System.out.println(length);
            }
            int baseWith = w60/length;
            System.out.println("BaseWith："+baseWith);
            fontSize = fontSize < baseWith ? baseWith : fontSize;
            LineHeight = fontSize + 5;
//            fontSize = baseWith;
//            LineHeight = baseWith + 5;
//            System.out.println(fontSize);
            System.out.println("fontSize："+fontSize);
            System.out.println("LineHeight："+LineHeight);

            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufferedImage.createGraphics();
            //设置“抗锯齿”的属性
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            g.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setColor(color);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            int width_1 = fontSize * getLength(textStr[0]);
            int height_1 = fontSize;
            int widthDiff = width - width_1;
//            int heightDiff = height - height_1;
            int heightDiff = height_1;
            System.out.println("heightDiff："+heightDiff);
            if (x < 0) {
                x = widthDiff / 2;
            } else if (x > widthDiff) {
                x = widthDiff;
            }
           /* if(y < 0){
                y = heightDiff / 2;
            }else if(y > heightDiff){
                y = heightDiff;
            }*/
//            int y = heightDiff + (LineHeight*textStr.length) ;
            int y = heightDiff ;
            System.out.println("y："+y);
//            if (StringUtils.equals("ios", type)) {
//                y = heightDiff - 100;
//            } else {
//                y = heightDiff - 100;
//            }

//            for(int i = 0;i<textStr.length;i++){
//                g.drawString(textStr[i], x, y + height_1 + (LineHeight*i));
//            }
            int nameSize = fontSize;
            int timeSize = nameSize - (nameSize/4);
            int daySize = nameSize/2;
            int addressSize = daySize;
            int lnglatSize = daySize;
            int time = x+nameSize*textStr[0].length() + 20;


            g.setFont(new Font(fontName, fontStyle, nameSize));
            g.drawString(textStr[0], x, y+timeSize/4);//姓名
            g.setFont(new Font(fontName, fontStyle, timeSize));
            g.drawString(textStr[1], time, y-timeSize/4);//时间
            g.setFont(new Font(fontName, fontStyle, daySize));
            g.drawString(textStr[2], time, y + timeSize-timeSize/3);//日期
            g.drawString(textStr[3], x, y + nameSize+timeSize/3);//地址
            g.drawString(textStr[4], x, y + nameSize + daySize +timeSize);//经纬度

            g.dispose();
            ImageIO.write(bufferedImage, PICTRUE_FORMATE, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static InputStream pressText(InputStream inputStream,String suffix, String pressText, String fontName, int fontStyle, int fontSize, Color color, int x, float alpha, int LineHeight) {
        try {

            //获取图片格式（如png,jpg等）
            String PICTRUE_FORMATE = suffix;
            Image image = ImageIO.read(inputStream);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            System.out.println("Height："+height);
            String textStr[] = pressText.split("_");//解析地理位置，经度，纬度

            Integer w60 = Double.valueOf(width*0.9).intValue();

            int length = 1;
            for(String str : textStr){
                length = str.length() < length ? length : str.length();
                System.out.println(length);
            }
            int baseWith = w60/length;
            System.out.println("BaseWith："+baseWith);
            fontSize = fontSize < baseWith ? baseWith : fontSize;
            LineHeight = fontSize + 5;
//            fontSize = baseWith;
//            LineHeight = baseWith + 5;
//            System.out.println(fontSize);
            System.out.println("fontSize："+fontSize);
            System.out.println("LineHeight："+LineHeight);

            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufferedImage.createGraphics();
            //设置“抗锯齿”的属性
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            g.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setColor(color);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            int width_1 = fontSize * getLength(textStr[0]);
            int height_1 = fontSize;
            int widthDiff = width - width_1;
//            int heightDiff = height - height_1;
            int heightDiff = height_1;
            System.out.println("heightDiff："+heightDiff);
            if (x < 0) {
                x = widthDiff / 2;
            } else if (x > widthDiff) {
                x = widthDiff;
            }
           /* if(y < 0){
                y = heightDiff / 2;
            }else if(y > heightDiff){
                y = heightDiff;
            }*/
//            int y = heightDiff + (LineHeight*textStr.length) ;
            int y = heightDiff ;
            System.out.println("y："+y);
//            if (StringUtils.equals("ios", type)) {
//                y = heightDiff - 100;
//            } else {
//                y = heightDiff - 100;
//            }

//            for(int i = 0;i<textStr.length;i++){
//                g.drawString(textStr[i], x, y + height_1 + (LineHeight*i));
//            }
            int nameSize = fontSize;
            int timeSize = nameSize - (nameSize/4);
            int daySize = nameSize/2;
            int addressSize = daySize;
            int lnglatSize = daySize;
            int time = x+nameSize*textStr[0].length() + 20;


            g.setFont(new Font(fontName, fontStyle, nameSize));
            g.drawString(textStr[0], x, y+timeSize/4);//姓名
            g.setFont(new Font(fontName, fontStyle, timeSize));
            g.drawString(textStr[1], time, y-timeSize/4);//时间
            g.setFont(new Font(fontName, fontStyle, daySize));
            g.drawString(textStr[2], time, y + timeSize-timeSize/3);//日期
            if(textStr.length-1 >= 3){
                g.drawString(textStr[3], x, y + nameSize+timeSize/3);//地址
            }
            if(textStr.length-1 >= 4){
                g.drawString(textStr[4], x, y + nameSize + daySize +timeSize);//经纬度
            }

            g.dispose();
//            ImageIO.write(bufferedImage, PICTRUE_FORMATE, file);
            return getImageStream(bufferedImage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    public static InputStream getImageStream(BufferedImage bimage){
        InputStream is = null;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imOut;
        try {
            imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(bimage, "png",imOut);
            is= new ByteArrayInputStream(bs.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

    /**
     * 获取字符长度，一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
     *
     * @param text
     * @return 字符长度，如：text="中国",返回 2；text="test",返回 2；text="中国ABC",返回 4.
     */
    public static int getLength(String text) {
        int textLength = text.length();
        int length = textLength;
        for (int i = 0; i < textLength; i++) {
            if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
                length++;
            }
        }
        return (length % 2 == 0) ? length / 2 : length / 2 + 1;
    }

    public static String renameSmallImg(String imgPath) {
        String ext = FilenameUtils.getExtension(imgPath);
        String fname = FilenameUtils.getBaseName(imgPath);
        String full = FilenameUtils.getFullPath(imgPath);
        return String.format("%s%s_s.%s", full, fname, ext);
    }

    public static boolean isImage(File file) throws IOException {
        String mimeType = java.nio.file.Files.probeContentType(file.toPath());

        if (mimeType != null) {
            return mimeType.startsWith("image/");
        } else {
            // 如果无法确定文件类型，则可以根据文件扩展名来判断
            String fileName = file.getName();
            int dotIndex = fileName.lastIndexOf(".");
            if (dotIndex != -1 && dotIndex < fileName.length() - 1) {
                String fileExtension = fileName.substring(dotIndex + 1);
                String[] imageExtensions = {"jpg", "jpeg", "png", "gif", "bmp"};
                for (String ext : imageExtensions) {
                    if (fileExtension.equalsIgnoreCase(ext)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    public static boolean isImageType(String suffix) {
        String[] imageExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        for (String ext : imageExtensions) {
            if (suffix.equalsIgnoreCase(ext)) {
                return true;
            }
        }
        return false;
    }

    public static BufferedImage generateThumbnail(MultipartFile imageFile) throws IOException {
        if (imageFile == null || imageFile.isEmpty()) {
            throw new IllegalArgumentException("Image file is null or empty");
        }

        BufferedImage originalImage = ImageIO.read(imageFile.getInputStream());
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        int newWidth = 100;
        int newHeight = (originalHeight * newWidth) / originalWidth;

        BufferedImage thumbnail = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        thumbnail.getGraphics().drawImage(originalImage.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);

        return thumbnail;
    }

    public static void saveThumbnail(MultipartFile imageFile, String thumbnailPath,String fileName) throws IOException {
        BufferedImage thumbnail = generateThumbnail(imageFile);
        String fileExtension = org.springframework.util.StringUtils.getFilenameExtension(imageFile.getOriginalFilename());

        // You can save the thumbnail as a file
        File thumbnailFile = new File(thumbnailPath + "/"+ fileName);
        ImageIO.write(thumbnail, fileExtension, thumbnailFile);
    }

    public static void main(String[] args) {
//        String text = "陈荣瑜_01:54_2022.06.06_福建省厦门市集美区杏林街道宁宝花园文达路21号4梯507室_118.998989 24.99876878";
//        pressText("/Users/rony/data/ddd90180c19140069318ddf186a3ef77.jpg",text,"宋体", Font.TRUETYPE_FONT,65,Color.WHITE,10,0.8f,30);
        try {
            ///Users/rony/work/data/upload/temp/2023/10
            File file = new File("/Users/rony/Desktop/WechatIMG770.jpeg");
            MultipartFile imageFile = FileUtils.fileToMultipartFile(file); // Replace with the actual MultipartFile
            String thumbnailPath = "/Users/rony/data/upload/temp/2023/10/26"; // Replace with the desired path

            saveThumbnail(imageFile, thumbnailPath,"WechatIMG770.jpeg");
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String fileName = "2023/10/26/643ce0337c3d4fac9cc7035afb52714a.jpeg";
//        String thumbFileName = fileName.substring(0,fileName.lastIndexOf("/"))+"/thumb_"+fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
//        System.out.println(thumbFileName);
    }
}
